package com.funo.logic.support;

import java.util.HashMap;
import java.util.Map;

/**
 * 枚举的map
 * 
 * @author fantasy
 * 
 */
public class EnumsCodeMap {
	private static Map<Class<?>, Map<Object, Object>> cache = new HashMap<>();

	@SuppressWarnings("unchecked")
	public static <E> E getValuedEnum(String code, Class<E> type) {
		final Map<Object, Object> value = cache.get(type);
		if (value == null) {
			final Map<Object, Object> tempMap = loadEnumMap(type);
			synchronized (cache) {
				cache.put(type, tempMap);
			}
			
			return (E) tempMap.get(code);
		}

		return (E) value.get(code);
	}

	private static Map<Object, Object> loadEnumMap(Class<?> type) {
		Map<Object, Object> map = new HashMap<>();
		final Object[] enums = type.getEnumConstants();
		if (enums == null) {
			throw new IllegalArgumentException(type.getSimpleName() + " does not represent an enum type.");
		}
		for (Object e : enums) {
			EnumsValue valuedEnum = (EnumsValue) e;
			map.put(valuedEnum.getCode(), e);
			map.put(((Enum)e).name(), e);
		}

		return map;
	}
}
